import { create } from 'zustand';
import { TerminalSession, ConnectionInfo } from '@shared/types';
import { v4 as uuidv4 } from 'uuid';

interface TerminalStore {
  // 会话列表
  sessions: TerminalSession[];
  activeSessionId: string | null;

  // 会话操作
  createSession: (connection: ConnectionInfo) => TerminalSession;
  closeSession: (sessionId: string) => void;
  setActiveSession: (sessionId: string) => void;
  updateSessionTitle: (sessionId: string, title: string) => void;
  addSessionHistory: (sessionId: string, command: string) => void;
  clearSessions: () => void;

  // 终端实例管理（用于SSH连接）
  terminalInstances: Map<string, any>;
  addTerminalInstance: (sessionId: string, instance: any) => void;
  removeTerminalInstance: (sessionId: string) => void;
  getTerminalInstance: (sessionId: string) => any | undefined;

  // 获取器
  getSessionById: (sessionId: string) => TerminalSession | undefined;
  getSessionsByConnection: (connectionId: string) => TerminalSession[];
  getActiveSession: () => TerminalSession | undefined;
}

export const useTerminalStore = create<TerminalStore>((set, get) => ({
  // 初始状态
  sessions: [],
  activeSessionId: null,
  terminalInstances: new Map(),

  // 创建新会话
  createSession: (connection) => {
    const now = new Date();
    const session: TerminalSession = {
      id: uuidv4(),
      connectionId: connection.id,
      title: connection.name,
      active: true,
      history: [],
      createdAt: now,
      lastActivity: now,
    };

    set((state) => ({
      sessions: [...state.sessions, session],
      activeSessionId: session.id,
    }));

    return session;
  },

  // 关闭会话
  closeSession: (sessionId) => {
    set((state) => {
      const sessions = state.sessions.filter((s) => s.id !== sessionId);
      let activeSessionId = state.activeSessionId;

      // 如果关闭的是当前活跃的会话，切换到其他会话
      if (activeSessionId === sessionId && sessions.length > 0) {
        activeSessionId = sessions[sessions.length - 1].id;
      } else if (sessions.length === 0) {
        activeSessionId = null;
      }

      return { sessions, activeSessionId };
    });

    // 清理终端实例
    get().removeTerminalInstance(sessionId);
  },

  // 设置活跃会话
  setActiveSession: (sessionId) => {
    set({ activeSessionId: sessionId });
  },

  // 更新会话标题
  updateSessionTitle: (sessionId, title) => {
    set((state) => ({
      sessions: state.sessions.map((s) =>
        s.id === sessionId ? { ...s, title, lastActivity: new Date() } : s
      ),
    }));
  },

  // 添加命令历史
  addSessionHistory: (sessionId, command) => {
    set((state) => ({
      sessions: state.sessions.map((s) =>
        s.id === sessionId
          ? {
              ...s,
              history: [...s.history, command],
              lastActivity: new Date(),
            }
          : s
      ),
    }));
  },

  // 清除所有会话
  clearSessions: () => {
    set({
      sessions: [],
      activeSessionId: null,
      terminalInstances: new Map(),
    });
  },

  // 添加终端实例
  addTerminalInstance: (sessionId, instance) => {
    set((state) => {
      const terminalInstances = new Map(state.terminalInstances);
      terminalInstances.set(sessionId, instance);
      return { terminalInstances };
    });
  },

  // 移除终端实例
  removeTerminalInstance: (sessionId) => {
    set((state) => {
      const terminalInstances = new Map(state.terminalInstances);
      terminalInstances.delete(sessionId);
      return { terminalInstances };
    });
  },

  // 获取终端实例
  getTerminalInstance: (sessionId) => {
    return get().terminalInstances.get(sessionId);
  },

  // 获取器
  getSessionById: (sessionId) => {
    return get().sessions.find((s) => s.id === sessionId);
  },

  getSessionsByConnection: (connectionId) => {
    return get().sessions.filter((s) => s.connectionId === connectionId);
  },

  getActiveSession: () => {
    const { sessions, activeSessionId } = get();
    return sessions.find((s) => s.id === activeSessionId);
  },
}));